<?php
/**
 * Created by PhpStorm.
 * User: Chris
 * Date: 15/3/26
 * Time: 下午10:02
 */

namespace Fuel\Tasks;

use Fuel\Core\DB;
use \Fuel\Core\Package;
use \Wolfteam\QueueService\RedisQueue;

// must be load the package at first , because we've extends the \Wolfteam\Task\BaseTask
Package::load('wolfteam');

class RedisQueueTask {


    // 子类需覆盖自定义参数
    protected static $REDIS_QUEUE_KEY = "THE_QUEUE_KEY"; // redis queue key
    protected static $REDIS_QUEUE_WAIT_SEC = 10; // 每次 redis pop等待时间


    protected $counter = 0;
    protected $startDate;


    protected static function log($msg){
        print date("Y-m-d H:i:s") . " [".getmypid()."] - $msg\r\n";
    }

    protected function keepDBAlive($db){
        DB::query('SELECT now()')->execute($db);
    }


    /**
     * 持续执行，绝不退出
     */
    public function run(){
        $this->startDate = date('Ymd');
        while (true){
            if ( $this->counter%5==0 ){
                // 每隔5秒，执行一次, 使用自定义的方法
                $this->keepDBAlive('master_db');
                $this->keepDBAlive('slave_db');
                if ($this->isTimeToExit()){
                    static::log("Time to exit!");
                    return;
                }
            }

            try {
                $decodeJson = true;
                /*
                 * the key has been add prefix ,  pls define the prefix in the config file (wolfteam.php)
                    'queueservice'=>array(
                        'redis_keyprefix'=>'WOLFTEAM_',
                    ),
                 */
                $queueObj = RedisQueue::blockPopQueue(
                    static::$REDIS_QUEUE_KEY,
                    static::$REDIS_QUEUE_WAIT_SEC,
                    $decodeJson);
                if ($queueObj) {
                    // We've pop an obj from queue!
                    $obj = $queueObj['key'];

                    $this->processObj($obj);
                }
            }catch (\Exception $e){
                // should be error, never quit!
                static::log("Error :". $e->getMessage());
                static::log($e->getTraceAsString());
            }
            usleep(10);
            $this->counter++;
        }
    }

    protected function isTimeToExit(){
        $now = date('Ymd');
        return $this->startDate!=$now;
    }

    protected function processObj($obj){
        // @todo: do your business here!
    }


}